package com.beidouin.sensortest;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.friendlyarm.AndroidSDK.FileCtlEnum;
import com.friendlyarm.AndroidSDK.HardwareControler;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

import static com.HardWare.PCF8591.ADC_Init;

public class HeartbeatActivity extends AppCompatActivity implements Runnable, CheckBox.OnCheckedChangeListener {

    public int size;
    private SimpleChartView cView;
    private static Context context;
    TextView adChannel;
    boolean adChannelIsChecked;
    int devFD = -1;
    Handler handler;
    Thread t = new Thread(this);

    public void setLife(boolean life) {
        this.life = life;
    }

    private static final int PORT = 8888;

    // (int) ((Math.random() * 9 + 1) * 1000);
    private int PCPORT = PORT;
    private byte[] msg = new byte[1024];
    private boolean life = true;
    private InetAddress pcadd = null;
    Button connect = null;
    TextView ipadd = null;
    TextView port = null;
    TextView heartbeat = null;
    ImageView img = null ;
    private Thread thread = null;
    /////////////////////////心率计算相关变量
    public int first, second, thrid;
    int fir, sec;/////////////时间
    int beat = 0;///心跳次数
    int lastbeat = 0, lastalstbeat = 0;
    int picturebeat = 0;
    int firsttime = 1;
    /////////////////////////////////////////
    public int heart[] = {
            96, 97, 98, 99, 102, 105, 115, 102, 96, 94, 96, 96,
            96, 97, 98, 99, 102, 105, 115, 102, 96, 94, 96, 96,
            96, 97, 98, 99, 102, 105, 115, 102, 96, 94, 96, 96,
            96, 97, 98, 99, 102, 105, 115, 102, 96, 94, 96, 96,
            96, 97, 98, 99, 102, 105, 115, 102, 96, 94, 96, 96,

            96, 97, 98, 99, 102, 105, 115, 102, 96, 94, 96, 96,
            96, 97, 98, 99, 102, 105, 115, 102, 96, 94, 96, 96,
            96, 97, 98, 99, 102, 105, 115, 102, 96, 94, 96, 96,
            96, 97, 98, 99, 102, 105, 115, 102, 96, 94, 96, 96,
            96, 97, 98, 99, 102, 105, 115, 102, 96, 94, 96, 96,

            96, 97, 98, 99, 102, 105, 115, 102, 96, 94, 96, 96,
            96, 97, 98, 99, 102, 105, 115, 102, 96, 94, 96, 96,
            96, 97, 98, 99, 102, 105, 115, 102, 96, 94, 96, 96,
            96, 97, 98, 99, 102, 105, 115, 102, 96, 94, 96, 96,
            96, 97, 98, 99, 102, 105, 115, 102, 96, 94, 96, 96,
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_heartbeat);
        context = getApplicationContext();
        cView = (SimpleChartView) findViewById(R.id.simpleChartView);
     //   adChannel = (TextView) findViewById(R.id.adtxvv1);
        heartbeat = (TextView) findViewById(R.id.heartbeat);

        adChannelIsChecked = false;
        devFD = HardwareControler.open("/dev/i2c-0", FileCtlEnum.O_RDWR);
        ADC_Init(devFD);

       // connect =  (Button) findViewById(R.id.send);
        ipadd = (TextView) findViewById(R.id.IPADD);
       // port = (TextView) findViewById(R.id.PORT);
        heartbeat = (TextView) findViewById(R.id.heartbeat);
        img = (ImageView) findViewById(R.id.imageView);

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 0x101) {
                  //  adChannel.setText(" " + msg.getData().getInt("ad0"));
                    heartbeat.setText(beat + " 次/秒");
                    if (picturebeat > 0) {
                        picturebeat--;
                        img.setImageResource(R.drawable.heart);
                    } else {
                        img.setImageResource(R.drawable.heart2);
                    }
                }
                super.handleMessage(msg);
            }
        };
        t.start();
    }

    public static String getHostIP() {
        try {
            Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces();

        } catch (SocketException e) {
            e.printStackTrace();
        }
        //获取IP地址
        WifiManager wifimanage = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiinfo = wifimanage.getConnectionInfo();
        int IPArr = wifiinfo.getIpAddress();

            /*String ip = ((IPArr >> 24) & 0xFF) + "." + ((IPArr >> 16) & 0xFF) + "" +
                    "." + ((IPArr >> 8) & 0xFF) + "." + (IPArr & 0xFF);*/
        String ip = (IPArr & 0xFF) + "." + ((IPArr >> 8) & 0xFF) + "" +
                "." + ((IPArr >> 16) & 0xFF) + "." + ((IPArr >> 24) & 0xFF);
        return ip;

    }

    @Override
    protected void onDestroy() {
        //将线程销毁掉
        HardwareControler.close(devFD);
        t.interrupt();
        super.onDestroy();
    }

    //@Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            Message m = handler.obtainMessage();
            Bundle bundle = new Bundle();
            m.what = 0x101;
            int[] ad = new int[4];
            for (int i = 0; i < 4; i++) {
                ad[i] = com.HardWare.PCF8591.readADC_bychannel(devFD, i);
            }
        /*    if (cView.datas.size() > 0) {
                // size = cView.datas.size();
                //cView.size=size;
                try {
                  //  pcadd = InetAddress.getByName(ipadd.getText().toString());
                    // pcadd = InetAddress.getByName("192.168.2.139");
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                if (port.getText().toString().equals("")) {

                } else {
                    PCPORT = Integer.parseInt(port.getText().toString());
                }
                int k;


            }
*/
            //cView.datas.add(heart[cView.size]);
            cView.datas.add(ad[0]);

            String s;
            s = String.valueOf(ad[0] + "\r\n" + "心率：" + beat + "次/分" + "\r\n" + "beat" + picturebeat);
            Thread sendthread = new Thread(new sendthread(s, pcadd, PCPORT));
            sendthread.start();
            handler.post(runnableUi);
            /////////////////////////////////////////////////////心率计算////////////////////
            if (first == 1) {
                if (ad[0] > 130) {
                    second = 1;
                    //开始时间（Unix时间戳）
                    sec = (int) (System.currentTimeMillis());
                    int beat2 = -60000 / (fir - sec);
                    first = second = 0;

                    if (beat2 > 200 || beat2 < 60) {
                        beat2++;
                    } else {
                        if (firsttime == 1) {////第一次
                            lastalstbeat = lastbeat = beat = beat2;
                            firsttime = 0;
                        } else {
                            beat = lastalstbeat * 40 / 100 + lastbeat * 40 / 100 + beat2 * 20 / 100;
                            lastalstbeat = lastbeat;
                            lastbeat = beat;
                        }
                    }
                    picturebeat = cView.beat = 5;

                }
            } else if (ad[0] > 130) {
                first = 1;
                fir = (int) (System.currentTimeMillis());
            }
            /////////////////////////////////////////////////////////////////////////////////
            bundle.putInt("ad0", ad[0]);
            //bundle.putInt("ad0",heart[cView.size]);
            bundle.putInt("ad1", ad[1]);
            bundle.putInt("ad2", ad[2]);
            bundle.putInt("ad3", ad[3]);
            m.setData(bundle);
            ////////////////////////对一组数据进行处理
            handler.sendMessage(m);
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {

        } else {
            switch (buttonView.getId()) {


            }
        }
    }

    Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            //更新界面
            cView.invalidate();
        }

    };
}
